// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-23

package distance

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 会员开关.
type Logic struct {
	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	affects     int64
	kind        kind.ArcadeAdminOperation
	kindContent string

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置日志.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, o.kind, o.kindContent,
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)

	// 1. 保存状态.
	if err = o.RunUpdate(ctx); err != nil {
		return res.WithError(err)
	}

	// 2. 保存完成.
	o.response.ShopDistance = o.request.Distance
	return res.With(o.response)
}

// RunUpdate
// 修改销售范围.
func (o *Logic) RunUpdate(ctx context.Context) (err error) {
	// 1. 不需修改.
	if o.request.Distance == o.arcade.ShopDistance {
		return
	}

	// 2. 保存状态.
	if o.affects, err = services.NewArcadesService().Dao.UpdateFieldsById(ctx, map[string]any{
		"shop_distance": o.request.Distance,
	}, o.arcade.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else if o.affects > 0 {
		o.kind = kind.ArcadeAdminOperationShopDistance
		o.kindContent = o.kind.ToShopDistance(o.arcade.ShopDistance, o.request.Distance)
	}
	return
}
